package app.controllers;

import app.models.sys.Module;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jfinal.aop.Before;
import com.jfinal.ext.interceptor.GET;
import com.jfinal.kit.JsonKit;
import goja.StringPool;
import goja.lang.Lang;
import goja.mvc.Controller;
import goja.rapid.datatables.DTCriterias;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.Map;

import static goja.StringPool.PK_COLUMN;


/**
 * <p>
 * 系统模块资源管理
 * </p>
 *
 * @author liuhui
 * @version 1.0
 * @since JDK 1.6
 */
public class ModuleController extends Controller {

    public void index(){

    }

    /**
     * 列表访问
     */
    @Before(GET.class)
    public void dtlist() {
        final DTCriterias criterias = getCriterias();
        renderDataTables(criterias, Module.class);
    }


    public void tree() {
        List<Module> modules = Module.dao.findAll();

        List<Map<String,Object>> treeNodeDtos = Lists.newArrayList();
        if (!Lang.isEmpty(modules)) {
            for (Module module : modules) {
                Map<String,Object> treeNode = Maps.newHashMap();
                treeNode.put(PK_COLUMN, module.getStr(PK_COLUMN));
                final String parent = module.getStr("parent");
                if(!StringUtils.equals(parent, StringPool.ZERO)){
                    treeNode.put("pId", parent);
                }
                treeNode.put("open", false);
                treeNode.put("name", module.getStr("name"));

                treeNodeDtos.add(treeNode);
            }
        }

        renderText(JsonKit.toJson(treeNodeDtos));


    }
}
